<?php

class AjaxController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'ajaxOnly +index +setRegion +filter',
            'postOnly +search',
        );
    }

    public function actionIndex() {
        echo 'Tumba';
    }

    public function actionFilter() {
        if (isset($_POST['ids'])) {
            $ids = explode('/', $_POST['ids']);
            $ids = array_map('intval', $ids);
            $region = $this->getRegion();
            $sql = 'SELECT
                        pr.*, p.prod_title, p.prod_url, p.prod_count, p.prod_image
                       FROM
                        mp_products P
                       LEFT JOIN mp__pr_prices pr ON pr.prod_id = P .prod_id AND pr.region_id = ' . $region['id'] . '
                       WHERE p.prod_id IN (SELECT prod_id FROM mp_prod2ch WHERE ch_id IN (' . implode(',', $ids) . ')) ORDER BY p.prod_sort';
            $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
            echo count($models);
            Yii::app()->end();
        }
    }

    public function actionSetRegion() {
        $id = (int) $_POST['id'];
        echo $this->setRegion($id) ? 'sucсess' : 'error';
    }

    public function actionSearch() {
        if (empty($_POST['q']))
            return false;
        $purifier = new CHtmlPurifier();
        $text = $purifier->purify($_POST['q']);
        $models = $this->getResult(mb_strtoupper($text, 'utf8'));
        if (Yii::app()->request->isAjaxRequest) {
            foreach ($models as $row) {
                $title = preg_replace('/(' . $text . ')/Uisu', '<strong>$1</strong>', $row['prod_title']);
                $result[] = array('url' => $row['prod_url'], 'title' => $title, 'articul' => $row['prod_mspares_artikul']);
            }
            if (!isset($result))
                return false;
            echo json_encode($result);
            Yii::app()->end();
        }
        $this->render('search', array('models' => $models, 'q' => $text));
    }

    public function getResult($str) {
        $region = $this->getRegion();
        $str = explode("-", $str);
        $str[0] = explode(" ", $str[0]);
        foreach ($str[0] as $key => $st) {
            if (!empty($st))
                $str[0][$key] = "(upper(p.prod_title) like '%" . $st . "%')";
            else
                unset($str[0][$key]);
        }
        $str[0][] = "p.prod_active = 1 ";
        $query = "SELECT pr.*, p.prod_title, p.prod_url, p.prod_count, p.prod_image, p.prod_id FROM mp_products p LEFT JOIN mp__pr_prices pr ON pr.prod_id = p.prod_id AND pr.region_id=" . $region['id'] . " WHERE " . implode(" AND ", $str[0]);
        if (isset($str[1])) {
            $str[1] = explode(" ", $str[1]);
            foreach ($str[1] as $key => $st) {
                if (!empty($st))
                    $str[1][$key] = "(upper(p.prod_title) NOT LIKE '%" . $st . "%')";
                else
                    unset($str[1][$key]);
            }
            if (!empty($str[1]))
                $query .= " AND ( " . implode(" AND ", $str[1]) . " ) ";
        }
        return Yii::app()->db->getCommandBuilder()->createSqlCommand($query)->queryAll();
    }

}
